package com.example.suuu.project.system.service.impl;

import cn.hutool.core.lang.ObjectId;
import com.example.suuu.config.exception.AppException;
import com.example.suuu.project.system.entity.SuUser;
import com.example.suuu.project.system.entity.SuUserRole;
import com.example.suuu.project.system.entity.vo.MyUserDetails;
import com.example.suuu.project.system.entity.vo.UserRoleCode;
import com.example.suuu.project.system.mapper.SuUserMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.suuu.project.system.service.SuUserService;
import com.example.suuu.tools.JsonUtil;
import com.example.suuu.tools.jwt.JwtUtils;
import com.example.suuu.tools.security.SecurityUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import com.example.suuu.model.PagVo;
import com.example.suuu.project.system.query.SuUserQuery;

/**
* <p>
    * 用户表 服务实现类
    * </p>
*
* @author sun
* @date 2023-06-28
*/
@Transactional
@Service
public class SuUserServiceImpl extends ServiceImpl<SuUserMapper, SuUser> implements SuUserService{
    @Resource
    PasswordEncoder passwordEncoder;
    @Resource
    UserDetailsService userDetailsService;
    @Resource
    private SuUserMapper suUserMapper;



    @Override
    public Object login(String username, String password) {
        try {
            MyUserDetails userDetails = (MyUserDetails) userDetailsService.loadUserByUsername(username);
            if (!passwordEncoder.matches(password, userDetails.getPassword())) {
                throw new AppException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new
                    UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            SuUser u = SecurityUtils.LoginUsers();
            String token = JwtUtils.generateToken(u.getUsercode(), JsonUtil.getJSON(u));
            return token;
        } catch (AuthenticationException e) {
            throw new AppException("登录失败");
        }
    }
    @Override
    public SuUser getByUsername(String username) {
        return suUserMapper.getByUsername(username);
    }

    @Override
    public int insertBatch(UserRoleCode userRoleCode) {
        List<SuUserRole> u = new ArrayList<>();
        for (String rolecode : userRoleCode.getRolecodes()) {
            SuUserRole r = new SuUserRole();
            r.setUsercode(userRoleCode.getUsercode());
            r.setRolecode(rolecode);
            u.add(r);
        }
        suUserMapper.delusercode(userRoleCode.getUsercode());
        return suUserMapper.insertBatch(u);
    }

    /**
    * 查询全部
    */
    @Override
    public List<SuUser> getList(SuUser u){
        return suUserMapper.getList(u);
    };
    /**
    * 查询总数
    */
    @Override
    public Long count(SuUser u){
        return suUserMapper.count(u);
    };
    /**
    * 查询单个
    */
    @Override
    public SuUser getById(Integer id){
        return suUserMapper.getById(id);
    };
    /**
    * 新增
    */
    @Override
    public int add(SuUser u){
        u.setIsdel(1);
        u.setPassword(passwordEncoder.encode(u.getPassword()));
        u.setUsercode(ObjectId.next());
        u.setCreatetime(LocalDateTime.now());
        u.setUpdatetime(LocalDateTime.now());
        return suUserMapper.add(u);
    };
    /**
    * 修改
    */
    @Override
    public int update(SuUser u){
        if(!u.getPassword().isEmpty()){
            u.setPassword(passwordEncoder.encode(u.getPassword()));
        }
        u.setUpdatetime(LocalDateTime.now());
        return suUserMapper.update(u);
    };
    /**
    * 删除
    */
    @Override
    public int del(Integer id){
        return suUserMapper.del(id);
    };

    /**
    * 分页区分方法
    */
    @Override
    public Object pagVo(SuUserQuery query){
        SuUser u = new SuUser();
        u.setIsdel(1);
        if (query.getCurrentPage() != null && query.getPageSize() != null) {
            u.setCurrentPage((query.getCurrentPage()-1)*query.getPageSize());
            u.setPageSize(query.getPageSize());
            PagVo p = new PagVo();
            p.setCount(count(u));
            p.setList(getList(u));
            return p;
        }
        return getList(u);
    }

}